package com.be.beadmin.system.controller.ProjectDesignController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.project.dto.input.ProductInfoDto;
import com.be.beadmin.project.dto.input.ProductInfosDto;
import com.be.beadmin.project.dto.input.ProductInfosExcelDto;
import com.be.beadmin.project.entity.ProductInfo;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.system.service.ProjectDesignSevice.ProductInfoPdService;
import com.google.common.io.ByteStreams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description:
 * @author: Jiaming Zheng
 * @Date: Create in 9:46 2023/6/20
 * @Modified By:
 **/
@Api(tags = {"项目-设计公共模块-柜体信息"})
@RestController
public class ProductInfoPdController {


    @Autowired
    private ProductInfoPdService productInfoPdService;

    @Autowired
    private MinioService minioService;




    @ApiOperation("添加柜体信息")
    @PostMapping("/project/addProductInfos")
    public ResultModel addProductInfos(HttpServletRequest request, @RequestBody ProductInfosDto productInfosDto){
        List<ProductInfo> productInfoList =  productInfoPdService.addProductInfos(request,productInfosDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @ApiOperation("批量添加柜体信息")
    @PostMapping("/project/addProductInfosByExcel")
    public ResultModel addProductInfosByExcel(
            HttpServletRequest request,
            @ApiParam(value = "上传Excel", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "infoId",required = true) @RequestParam("infoId") String infoId) {
        AtomicInteger a= new AtomicInteger();
        try {
            EasyExcel.read(file.getInputStream(), ProductInfosExcelDto.class, new PageReadListener<ProductInfosExcelDto>(dataList -> {
                for (ProductInfosExcelDto productInfosExcelDto : dataList) {
                    ProductInfosDto productInfosDto = new ProductInfosDto();
                    productInfosDto.setInfoId(infoId);
                    productInfosDto.setProductQty(1);
                    BeanUtils.copyProperties(productInfosExcelDto, productInfosDto);
                    if (Objects.equals(productInfosExcelDto.getStandard(), "是") || Objects.equals(productInfosExcelDto.getStandard(), "1")) {
                        productInfosDto.setIsStandard(BigDecimal.valueOf(1));
                    } else if (Objects.equals(productInfosExcelDto.getStandard(), "否") || Objects.equals(productInfosExcelDto.getStandard(), "0"))
                        productInfosDto.setIsStandard(BigDecimal.valueOf(0));
                    productInfoPdService.addProductInfos(request, productInfosDto);
                }
                a.set(dataList.size());
            })).sheet().doRead();

        }catch (Exception e){
            return ResultModel.error(-3,"文件读取异常，请检查Excel文件");
        }
        return ResultModel.success("增加了"+a+"条记录");
    }


    @ApiOperation("下载Excel模版")
    @GetMapping("/project/downloadExcelTemplate")
    @ResponseBody
    public void downloadExcelTemplate(HttpServletResponse response){
//        standFileInfoService.downloadFile(bucketName,fileCode,response);
        try {

            String TemplateName= "柜体导入模板.xls";
            String Bucket="beadmin";
            InputStream inputStream = minioService.downloadOne(Bucket, TemplateName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+TemplateName);
            response.addHeader("Content-Type", "application/vnd.ms-excel;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();
            ByteStreams.copy(inputStream, os);
            os.flush();
            // return  ResultModel.success("下载成功");
        } catch (Exception e) {
            // return ResultModel.error(99,"文件读取异常");
        }
    }


    @ApiOperation("更新一条柜体信息")
    @PostMapping("/project/updateProductInfo")
    public ResultModel updateProductInfo(@RequestBody ProductInfoDto productInfoDto){
        try {
            productInfoPdService.updateProductInfo(productInfoDto);
            return ResultModel.success(ResultModel.UPDATE);
        } catch (BeadminException e) {
            return ResultModel.error(-1, e.getMessage());
        }

//        if (result==-10) return ResultModel.error(result,"该柜体已发布，无法删除");
//        if (result==-11) return ResultModel.error(result,"该柜体已下发，无法修改");
    }

    @ApiOperation("获取项目团队下所有的工程师（技术人员）")
    @PostMapping("project/getProjectTeamEngineers")
    public ResultModel getProjectTeamEngineers(@ApiParam("项目Id") @RequestParam String infoId){
        return ResultModel.success(productInfoPdService.getProjectTeamEngineers(infoId));
    }
}
